package com.sm.appbase.net.base;

import android.util.Log;


import com.sm.appbase.base.basemvp.BasePresenter;
import com.sm.appbase.base.basemvp.BaseView;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 上传文件的RxJava2回调
 */

public abstract class FileUploadObserver<T> implements Observer<T> {
    private BaseView view;
    private BasePresenter presenter;
    private boolean isShowDialog = true;

    public FileUploadObserver(BaseView view, BasePresenter presenter, boolean isShowDialog) {
        this.view = view;
        this.presenter = presenter;
        this.isShowDialog = isShowDialog;
    }

    @Override
    public void onSubscribe(Disposable d) {
        view.bindDispos(d);
        Log.e("progress", "onSubscribe: " + Thread.currentThread().getId());
        if ((presenter.isViewAttached()) && view != null && isShowDialog) {
            view.showLoading("正在上传");
        }
    }

    @Override
    public void onNext(T t) {
        onUpLoadSuccess(t);
        Log.e("progress", "onNext: " + Thread.currentThread().getId());
        if ((presenter.isViewAttached()) && view != null&& isShowDialog) {
            view.hideLoading();
        }
    }

    @Override
    public void onError(Throwable e) {
        onUpLoadFail(e);
        Log.e("progress", "onError: " + Thread.currentThread().getId());
        if ((presenter.isViewAttached()) && view != null&& isShowDialog) {
            view.hideLoading();
        }
    }

    @Override
    public void onComplete() {

        if ((presenter.isViewAttached()) && view != null&& isShowDialog) {
            view.hideLoading();
        }
    }

    //监听进度的改变
    public void onProgressChange(long bytesWritten, long contentLength) {
        onProgress((int) (bytesWritten * 100 / contentLength));
    }

    //上传成功的回调
    public abstract void onUpLoadSuccess(T t);

    //上传失败回调
    public abstract void onUpLoadFail(Throwable e);

    //上传进度回调
    public abstract void onProgress(int progress);

}
